import 'dart:developer';

import 'package:dio/dio.dart';
import 'package:edu/constants/app_strings.dart';
import 'package:edu/utils/account_info.dart';
import 'package:edu/utils/data_fetcher.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

class AcountPageLogic extends ChangeNotifier {
  bool get isLogin => AccountInfo.shared.isLoggedIn;

  void init() {
    AccountInfo.shared.userBriefNotifier.addListener(_userBriefListener);
  }

  @override
  void dispose() {
    super.dispose();
    AccountInfo.shared.userBriefNotifier.removeListener(_userBriefListener);
  }

  // 监听用户信息
  void _userBriefListener() {
    notifyListeners();
  }

  // 获取已学习天数
  int? get eduDays {
    final userBrief = AccountInfo.shared.userBrief;
    if (userBrief == null) {
      return null;
    }
    // 计算已学习天数,从创建时间开始
    final start = userBrief.createdAt;
    final end = DateTime.now();

    return end.difference(start).inDays;
  }

  // 获取已学习时长
  int get eduMinutes {
    return (AccountInfo.shared.eduSecondsNotifier.value ?? 0) ~/ 60;
  }

  // 获取用户昵称
  String? get nickName {
    final userBrief = AccountInfo.shared.userBrief;
    if (userBrief == null) {
      return '';
    }
    return userBrief.name;
  }

  // 获取用户性别
  String? get gender {
    final userBrief = AccountInfo.shared.userBrief;
    if (userBrief == null) {
      return '';
    }
    return userBrief.gender;
  }

  // 退出登录
  void logout() async {
    try {
      EasyLoading.show(
        indicator: const CircularProgressIndicator(),
        maskType: EasyLoadingMaskType.clear,
        dismissOnTap: false,
      );
      final response = await DataFetcher.shared.userApi.logout();
      if (response.code == 0) {
        await AccountInfo.shared.logout();
        EasyLoading.showSuccess(AppStrings.logoutSuccess);
      } else {
        EasyLoading.showError(AppStrings.logoutFailed);
        if (response.message != null) {
          log('${AppStrings.logoutFailed}: ${response.message}');
        }
      }
    } on DioException catch (e) {
      log('${AppStrings.logoutFailed}: ${e.toString()}');
    } finally {
      AccountInfo.shared.logout();
    }
  }
}
